package com.tsd.jxc.stock.job;

import com.tsd.core.annotation.TaskJob;
import com.tsd.core.annotation.TaskJobMethod;
import com.tsd.core.constants.Constants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.job.JobBaseClass;
import com.tsd.core.thread.ThreadPoolTaskUtil;
import com.tsd.core.utils.*;
import com.tsd.job.entity.SysTaskJobExt;
import com.tsd.job.service.SysTaskJobExecLogService;
import com.tsd.jxc.fin.FinanceConstants;
import com.tsd.jxc.stock.StockConstants;
import com.tsd.jxc.stock.dao.*;
import com.tsd.jxc.stock.entity.*;
import com.tsd.system.entity.SysUser;
import com.tsd.system.service.SysAccountSetService;
import com.tsd.utils.AutoInjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: JxcStockJob
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2022/8/17 14:19
 * @Version: 1.0
 */
@TaskJob(name = "库存定时任务", mode = FinanceConstants.MODE_JXC)
public class JxcStockJob extends JobBaseClass {

    public static final Logger LOGGER = LoggerFactory.getLogger(JxcStockJob.class);
    /**
     * 处理库存处理队列
     */
    private static boolean isStartProcJxcStockQueing = false;
    @Resource
    private SysAccountSetService sysAccountSetService;
    @Resource
    private SysTaskJobExecLogService sysTaskJobExecLogService;
    @Resource
    private JxcStockQueMapper jxcStockQueMapper;
    @Resource
    private JxcStockGoodsMapper jxcStockGoodsMapper;
    @Resource
    private JxcStockInbillMapper jxcStockInbillMapper;
    @Resource
    private JxcStockOutbillMapper jxcStockOutbillMapper;
    @Resource
    private JxcStockInventoryMapper jxcStockInventoryMapper;
    @Resource
    private JxcStockInventoryItemMapper jxcStockInventoryItemMapper;

    public void addJxcStockQue(String code, String bizName, String method, Long dataId, SysUser opUser) {
        JxcStockQueExt queExt = new JxcStockQueExt();
        queExt.setCode(code);
        queExt.setProc_type(1);
        queExt.setBiz_name(bizName);
        String beanName = HlpUtils.toLowerCaseFirstOne(JxcStockJob.class.getSimpleName());
        queExt.setBean_name(beanName);
        queExt.setMethod_name(method);
        queExt.setData_id(dataId);
        queExt.setState(Constants.VALUE_NO);
        AutoInjectUtils.autoInjectBaseData(queExt, opUser, AutoInjectUtils.TYPE_CREATE);
        jxcStockQueMapper.insertSelective(queExt);
    }

    /**
     * 加入优先队列
     *
     * @param accountSetSid
     */
    public void addAccountSet2PriorityQueue(String accountSetSid) {
        // 加入优先队列
        super.addPpriorityQueue(accountSetSid);
        // 启动
        ThreadPoolTaskUtil.execute(() -> {
            startProcJxcStockQue(null);
        });
    }

    @TaskJobMethod(name = "处理库存队列")
    public void startProcJxcStockQue(SysTaskJobExt jobExt) {
        LOGGER.info("处理库存处理队列：startProcJxcStockQue");
        if (!isStartProcJxcStockQueing) {
            isStartProcJxcStockQueing = true;
            super.fetchAccountSet("处理库存队列", this.getClass().getName(),
                    "startProcJxcStockQue", new CallBack() {
                        @Override
                        public int dealBody() {
                            procJxcStockQue();
                            return 0;
                        }

                        @Override
                        public void complete() {
                            isStartProcJxcStockQueing = false;
                        }
                    });
        }
    }

    public void procJxcStockQue() {
        LOGGER.info("账套：{}，处理库存处理队列：procJxcStockQue", DataSourceContextHolder.getDataSourceType());
        int pageSize = 100;
        List<JxcStockQueExt> queExtList;
        Long greaterThanId = null;
        do {
            queExtList = jxcStockQueMapper.select4Proc(greaterThanId, pageSize);
            if (HlpUtils.isEmptyList(queExtList)) {
                break;
            }
            for (JxcStockQueExt queExt : queExtList) {
                this.procOneRecordByRefect(queExt);
            }
            greaterThanId = queExtList.get(queExtList.size() - 1).getId();
        } while (queExtList.size() == pageSize);
    }

    private synchronized void procOneRecordByRefect(JxcStockQueExt queExt) {
        try {
            try {
                RefectUtil.springInvokeMethod(queExt.getBean_name(), queExt.getMethod_name(), new Object[]{queExt});
                queExt.setState(1);
                queExt.setResult_text(null);
            } catch (Exception e) {
                queExt.setState(-1);
                queExt.setResult_text(e.getMessage() + "\n" + ExceptionUtil.getStackTraceFromException(e));
            }
            queExt.setUpdate_date(new Date());
            jxcStockQueMapper.updateByPrimaryKey(queExt);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
    }


    /**
     * 更新库存数量
     * 表jxc_stock_goods_position字段：stock_qty
     *
     * @param queExt
     */
    public void updateStockQty2StockGoodsPosition(JxcStockQueExt queExt) {
        if (StockConstants.OPERATE_ADD.equals(queExt.getCode())) {
            this.updateStockQty2StockGoodsPosition4Add(queExt);
        } else {
            this.updateStockQty2StockGoodsPosition4Sub(queExt);
        }
    }

    private void updateStockQty2StockGoodsPosition4Add(JxcStockQueExt queExt) {
        if (StockConstants.BIZ_NAME_IN_BILL.equals(queExt.getBiz_name())) {
        }else{
            updateStockQty2StockGoodsPosition4AddOutBill(queExt);
        }
    }


    private void updateStockQty2StockGoodsPosition4AddOutBill(JxcStockQueExt queExt){
//        JxcStockOutbill outbill = jxcStockOutbillMapper.selectByPrimaryKey(queExt.getData_id());
//        if (outbill == null) {
//            return;
//        }
//        JxcStockOutbillItemPositionExt params = new JxcStockOutbillItemPositionExt();
//        params.setDr(0);
//        params.setOutbill_sid(outbill.getSid());
//        List<JxcStockOutbillItemPositionExt> positionExtList = jxcStockOutbillItemPositionMapper.selectByEntity(params);
//        if (HlpUtils.isEmptyList(positionExtList)) {
//            return;
//        }
//        List<String> productList = ListUtil.map(positionExtList, JxcStockOutbillItemPositionExt::getGoods_sid);
//        List<JxcStockGoodsPositionExt> list = jxcStockGoodsPositionMapper.selectValidByProductList(productList);
//
//        List<JxcStockGoodsPositionExt> insertList = new ArrayList<>();
//        List<JxcStockGoodsPositionExt> updateList = new ArrayList<>();
//        for (JxcStockOutbillItemPositionExt itemPositionExt : positionExtList) {
//            JxcStockGoodsPositionExt positionExt = ListUtil.get(list, t -> t.getGoods_sid().equals(itemPositionExt.getGoods_sid())
//                    && t.getPosition_sid().equals(itemPositionExt.getPosition_sid()));
//            if (positionExt == null) {
//                positionExt = JxcStockGoodsPositionExt.genNew(itemPositionExt);
//            }
//            double iningQty = DoubleUtil.sub(positionExt.getStock_qty_ining(), itemPositionExt.getOut_qty());
//            positionExt.setStock_qty_ining(BigDecimal.valueOf(iningQty));
//            double stockQty = DoubleUtil.add(positionExt.getStock_qty(), itemPositionExt.getOut_qty());
//            positionExt.setStock_qty(BigDecimal.valueOf(stockQty));
//            if (HlpUtils.isEmpty(positionExt.getId())) {
//                AutoInjectUtils.autoInjectBaseData(positionExt, null, AutoInjectUtils.TYPE_CREATE);
//                insertList.add(positionExt);
//            } else {
//                AutoInjectUtils.autoInjectBaseData(positionExt, null, AutoInjectUtils.TYPE_UPDATE);
//                updateList.add(positionExt);
//            }
//        }
//        if (!HlpUtils.isEmptyList(updateList)) {
//            ThreadPoolTaskUtil.executeInList4Split(updateList, false, dataList -> jxcStockGoodsPositionMapper.updateList(dataList));
//        }
//        if (!HlpUtils.isEmptyList(insertList)) {
//            ThreadPoolTaskUtil.executeInList4Split(insertList, false, dataList -> jxcStockGoodsPositionMapper.insertList(dataList));
//        }
//        this.updateStockSumQty2StockGoods4AddOutBill(positionExtList);
    }
    private void updateStockQty2StockGoodsPosition4Sub(JxcStockQueExt queExt) {
        if (StockConstants.BIZ_NAME_IN_BILL.equals(queExt.getBiz_name())) {
            updateStockQty2StockGoodsPosition4SubInBill(queExt);
        }else{
            updateStockQty2StockGoodsPosition4SubOutBill(queExt);
        }
    }

    /**
     * 取消入库操作的扣减库存
     * @param queExt
     */
    private void updateStockQty2StockGoodsPosition4SubInBill(JxcStockQueExt queExt) {
//        JxcStockInbill inbill = jxcStockInbillMapper.selectByPrimaryKey(queExt.getData_id());
//        if (inbill == null) {
//            return;
//        }
//        JxcStockInbillItemPositionExt params = new JxcStockInbillItemPositionExt();
//        params.setDr(0);
//        params.setInbill_sid(inbill.getSid());
//        List<JxcStockInbillItemPositionExt> positionExtList = jxcStockInbillItemPositionMapper.selectByEntity(params);
//        if (HlpUtils.isEmptyList(positionExtList)) {
//            return;
//        }
//        List<String> productList = ListUtil.map(positionExtList, JxcStockInbillItemPositionExt::getGoods_sid);
//        List<JxcStockGoodsPositionExt> list = jxcStockGoodsPositionMapper.selectValidByProductList(productList);
//
//        for (JxcStockInbillItemPositionExt itemPositionExt : positionExtList) {
//            JxcStockGoodsPositionExt positionExt = ListUtil.get(list, t -> t.getGoods_sid().equals(itemPositionExt.getGoods_sid())
//                    && t.getPosition_sid().equals(itemPositionExt.getPosition_sid()));
//            if (positionExt == null) {
//                positionExt = JxcStockGoodsPositionExt.genNew(itemPositionExt);
//            }
//            double iningQty = DoubleUtil.sub(positionExt.getStock_qty_ining(), itemPositionExt.getIn_qty());
//            positionExt.setStock_qty_ining(BigDecimal.valueOf(iningQty));
//            double stockQty = DoubleUtil.sub(positionExt.getStock_qty(), itemPositionExt.getIn_qty());
//            positionExt.setStock_qty(BigDecimal.valueOf(stockQty));
//            if (HlpUtils.isEmpty(positionExt.getId())) {
//                AutoInjectUtils.autoInjectBaseData(positionExt, null, AutoInjectUtils.TYPE_CREATE);
//                jxcStockGoodsPositionMapper.insert(positionExt);
//            } else {
//                AutoInjectUtils.autoInjectBaseData(positionExt, null, AutoInjectUtils.TYPE_UPDATE);
//                jxcStockGoodsPositionMapper.updateByPrimaryKey(positionExt);
//            }
//        }
//        this.updateStockSumQty2StockGoods4SubInBill(positionExtList);
    }
    private void updateStockQty2StockGoodsPosition4SubOutBill(JxcStockQueExt queExt) {
//        JxcStockOutbill outbill = jxcStockOutbillMapper.selectByPrimaryKey(queExt.getData_id());
//        if (outbill == null) {
//            return;
//        }
//        JxcStockOutbillItemPositionExt params = new JxcStockOutbillItemPositionExt();
//        params.setDr(0);
//        params.setOutbill_sid(outbill.getSid());
//        List<JxcStockOutbillItemPositionExt> positionExtList = jxcStockOutbillItemPositionMapper.selectByEntity(params);
//        if (HlpUtils.isEmptyList(positionExtList)) {
//            return;
//        }
//        List<String> productList = ListUtil.map(positionExtList, JxcStockOutbillItemPositionExt::getGoods_sid);
//        List<JxcStockGoodsPositionExt> list = jxcStockGoodsPositionMapper.selectValidByProductList(productList);
//
//        List<JxcStockGoodsPositionExt> insertList = new ArrayList<>();
//        List<JxcStockGoodsPositionExt> updateList = new ArrayList<>();
//        for (JxcStockOutbillItemPositionExt itemPositionExt : positionExtList) {
//            JxcStockGoodsPositionExt positionExt = ListUtil.get(list, t -> t.getGoods_sid().equals(itemPositionExt.getGoods_sid())
//                    && t.getPosition_sid().equals(itemPositionExt.getPosition_sid()));
//            if (positionExt == null) {
//                positionExt = JxcStockGoodsPositionExt.genNew(itemPositionExt);
//            }
//            double outingQty = DoubleUtil.sub(positionExt.getStock_qty_outing(), itemPositionExt.getOut_qty());
//            positionExt.setStock_qty_outing(BigDecimal.valueOf(outingQty));
//            double stockQty = DoubleUtil.sub(positionExt.getStock_qty(), itemPositionExt.getOut_qty());
//            positionExt.setStock_qty(BigDecimal.valueOf(stockQty));
//            if (HlpUtils.isEmpty(positionExt.getId())) {
//                AutoInjectUtils.autoInjectBaseData(positionExt, null, AutoInjectUtils.TYPE_CREATE);
//                insertList.add(positionExt);
//            } else {
//                AutoInjectUtils.autoInjectBaseData(positionExt, null, AutoInjectUtils.TYPE_UPDATE);
//                updateList.add(positionExt);
//            }
//        }
//        if (!HlpUtils.isEmptyList(updateList)) {
//            ThreadPoolTaskUtil.executeInList4Split(updateList, false, dataList -> jxcStockGoodsPositionMapper.updateList(dataList));
//        }
//        if (!HlpUtils.isEmptyList(insertList)) {
//            ThreadPoolTaskUtil.executeInList4Split(insertList, false, dataList -> jxcStockGoodsPositionMapper.insertList(dataList));
//        }
//        this.updateStockSumQty2StockGoods4SubOutBill(positionExtList);
    }


    /**
     * 更新库存合计数量(取消出库单后的增加）
     * 表jxc_stock_goods字段：stock_sum_qty
     *
     */
    private void updateStockSumQty2StockGoods4AddOutBill() {
//        if (HlpUtils.isEmptyList(positionExtList)) {
//            return;
//        }
//        List<String> productList = ListUtil.map(positionExtList, JxcStockOutbillItemPositionExt::getGoods_sid);
//        List<JxcStockGoodsExt> list = jxcStockGoodsMapper.selectValidByProductList(productList);
//        for (String productSid : productList) {
//            List<JxcStockOutbillItemPositionExt> filterList = ListUtil.filter(positionExtList, t -> t.getGoods_sid().equals(productSid));
//            if (HlpUtils.isEmptyList(filterList)) {
//                continue;
//            }
//            JxcStockGoodsExt goodsExt = ListUtil.get(list, t -> t.getGoods_sid().equals(productSid));
//            if (goodsExt == null) {
//                goodsExt = JxcStockGoodsExt.genNew(filterList.get(0));
//            }
//            if (HlpUtils.isEmpty(goodsExt.getStock_sum_qty())) {
//                goodsExt.setStock_sum_qty(BigDecimal.ZERO);
//            }
//            double totalQty = goodsExt.getStock_sum_qty().doubleValue();
//            for (JxcStockOutbillItemPositionExt positionExt : filterList) {
//                totalQty = DoubleUtil.add(totalQty, positionExt.getOut_qty());
//            }
//            goodsExt.setStock_sum_qty(BigDecimal.valueOf(totalQty));
//            if (HlpUtils.isEmpty(goodsExt.getId())) {
//                AutoInjectUtils.autoInjectBaseData(goodsExt, null, AutoInjectUtils.TYPE_CREATE);
//                jxcStockGoodsMapper.insertSelective(goodsExt);
//            } else {
//                AutoInjectUtils.autoInjectBaseData(goodsExt, null, AutoInjectUtils.TYPE_UPDATE);
//                jxcStockGoodsMapper.updateByPrimaryKeySelective(goodsExt);
//            }
//        }
    }
    /**
     * 更新库存合计数量(根据出库单减少数量）
     * 表jxc_stock_goods字段：stock_sum_qty
     *
     */
    private void updateStockSumQty2StockGoods4SubOutBill(){//List<JxcStockOutbillItemPositionExt> positionExtList) {
//        if (HlpUtils.isEmptyList(positionExtList)) {
//            return;
//        }
//        List<String> productList = ListUtil.map(positionExtList, JxcStockOutbillItemPositionExt::getGoods_sid);
//        List<JxcStockGoodsExt> list = jxcStockGoodsMapper.selectValidByProductList(productList);
//        List<JxcStockGoodsExt> insertList = new ArrayList<>();
//        List<JxcStockGoodsExt> updateList = new ArrayList<>();
//        for (String productSid : productList) {
//            List<JxcStockOutbillItemPositionExt> filterList = ListUtil.filter(positionExtList, t -> t.getGoods_sid().equals(productSid));
//            if (HlpUtils.isEmptyList(filterList)) {
//                continue;
//            }
//            JxcStockGoodsExt goodsExt = ListUtil.get(list, t -> t.getGoods_sid().equals(productSid));
//            if (goodsExt == null) {
//                goodsExt = JxcStockGoodsExt.genNew(filterList.get(0));
//            }
//            if (HlpUtils.isEmpty(goodsExt.getStock_sum_qty())) {
//                goodsExt.setStock_sum_qty(BigDecimal.ZERO);
//            }
//            double totalQty = goodsExt.getStock_sum_qty().doubleValue();
//            for (JxcStockOutbillItemPositionExt positionExt : filterList) {
//                totalQty = DoubleUtil.sub(totalQty, positionExt.getOut_qty());
//            }
//            goodsExt.setStock_sum_qty(BigDecimal.valueOf(totalQty));
//            if (HlpUtils.isEmpty(goodsExt.getId())) {
//                AutoInjectUtils.autoInjectBaseData(goodsExt, null, AutoInjectUtils.TYPE_CREATE);
//                insertList.add(goodsExt);
//            } else {
//                AutoInjectUtils.autoInjectBaseData(goodsExt, null, AutoInjectUtils.TYPE_UPDATE);
//                updateList.add(goodsExt);
//            }
//        }
//        if (!HlpUtils.isEmptyList(updateList)) {
//            ThreadPoolTaskUtil.executeInList4Split(updateList, false, dataList -> jxcStockGoodsMapper.updateList(dataList));
//        }
//        if (!HlpUtils.isEmptyList(insertList)) {
//            ThreadPoolTaskUtil.executeInList4Split(insertList, false, dataList -> jxcStockGoodsMapper.insertList(dataList));
//        }
    }
    /**
     * 更新库存合计数量(根据入库单减少）
     * 表jxc_stock_goods字段：stock_sum_qty
     *
     */
    private void updateStockSumQty2StockGoods4SubInBill(){//List<JxcStockInbillItemPositionExt> positionExtList) {
//        if (HlpUtils.isEmptyList(positionExtList)) {
//            return;
//        }
//        List<String> productList = ListUtil.map(positionExtList, JxcStockInbillItemPositionExt::getGoods_sid);
//        List<JxcStockGoodsExt> list = jxcStockGoodsMapper.selectValidByProductList(productList);
//        for (String productSid : productList) {
//            List<JxcStockInbillItemPositionExt> filterList = ListUtil.filter(positionExtList, t -> t.getGoods_sid().equals(productSid));
//            if (HlpUtils.isEmptyList(filterList)) {
//                continue;
//            }
//            JxcStockGoodsExt goodsExt = ListUtil.get(list, t -> t.getGoods_sid().equals(productSid));
//            if (goodsExt == null) {
//                goodsExt = JxcStockGoodsExt.genNew(filterList.get(0));
//            }
//            if (HlpUtils.isEmpty(goodsExt.getStock_sum_qty())) {
//                goodsExt.setStock_sum_qty(BigDecimal.ZERO);
//            }
//            double totalQty = goodsExt.getStock_sum_qty().doubleValue();
//            for (JxcStockInbillItemPositionExt positionExt : filterList) {
//                totalQty = DoubleUtil.sub(totalQty, positionExt.getIn_qty());
//            }
//            goodsExt.setStock_sum_qty(BigDecimal.valueOf(totalQty));
//            if (HlpUtils.isEmpty(goodsExt.getId())) {
//                AutoInjectUtils.autoInjectBaseData(goodsExt, null, AutoInjectUtils.TYPE_CREATE);
//                jxcStockGoodsMapper.insertSelective(goodsExt);
//            } else {
//                AutoInjectUtils.autoInjectBaseData(goodsExt, null, AutoInjectUtils.TYPE_UPDATE);
//                jxcStockGoodsMapper.updateByPrimaryKeySelective(goodsExt);
//            }
//        }
    }
    /**
     * 盘点单更新库存数量
     * 表jxc_stock_goods_position字段：stock_qty
     *
     */
    public void updateStockQty2StockGoodsPosition4Inventory(){//JxcStockQueExt queExt) {
//        JxcStockInventory inventory = jxcStockInventoryMapper.selectByPrimaryKey(queExt.getData_id());
//        // 应修改为根据 update_stock 判断是否更新 2 == inventory.getState()
//        if (inventory == null || 1 == inventory.getUpdate_stock()) {
//            return;
//        }
//        JxcStockInventoryItemExt params = new JxcStockInventoryItemExt();
//        params.setDr(0);
//        params.setInventory_sid(inventory.getSid());
//        List<JxcStockInventoryItemExt> itemExtList = jxcStockInventoryItemMapper.selectByEntity(params);
//        if (!HlpUtils.isEmptyList(itemExtList)) {
//            List<String> productList = ListUtil.map(itemExtList, JxcStockInventoryItemExt::getGoods_sid);
//            List<JxcStockGoodsPositionExt> list = jxcStockGoodsPositionMapper.selectValidByProductList(productList);
//            List<JxcStockGoodsPositionExt> insertList = new ArrayList<>();
//            List<JxcStockGoodsPositionExt> updateList = new ArrayList<>();
//            for (JxcStockInventoryItemExt itemExt : itemExtList) {
//                JxcStockGoodsPositionExt goodsExt = ListUtil.get(list, t -> t.getGoods_sid().equals(itemExt.getGoods_sid()) && t.getPosition_sid().equals(itemExt.getOld_position_sid()));
//                if (goodsExt == null) {
//                    continue;
//                }
//                if (HlpUtils.isEmpty(itemExt.getNew_position_sid())) {
//                    goodsExt.setStock_qty(itemExt.getCheck_qty());
//                    updateList.add(goodsExt);
//                    continue;
//                }
//                double value = DoubleUtil.sub(goodsExt.getStock_qty(), itemExt.getOld_qty());
//                goodsExt.setStock_qty(BigDecimal.valueOf(value));
//                updateList.add(goodsExt);
//
//                JxcStockGoodsPositionExt newGoodsExt = ListUtil.get(list, t -> t.getGoods_sid().equals(itemExt.getGoods_sid()) && t.getPosition_sid().equals(itemExt.getNew_position_sid()));
//                if (newGoodsExt == null) {
//                    newGoodsExt = JxcStockGoodsPositionExt.genNew(itemExt);
//                    insertList.add(newGoodsExt);
//                } else {
//                    value = DoubleUtil.add(newGoodsExt.getStock_qty(), itemExt.getCheck_qty());
//                    newGoodsExt.setStock_qty(BigDecimal.valueOf(value));
//                    updateList.add(newGoodsExt);
//                }
//            }
//            if (!HlpUtils.isEmptyList(updateList)) {
//                ThreadPoolTaskUtil.executeInList4Split(updateList, false, dataList -> jxcStockGoodsPositionMapper.updateList(dataList));
//            }
//            if (!HlpUtils.isEmptyList(insertList)) {
//                ThreadPoolTaskUtil.executeInList4Split(insertList, false, dataList -> jxcStockGoodsPositionMapper.insertList(dataList));
//            }
//        }
//
//        jxcStockGoodsMapper.updateStockQtyByInventory(inventory.getSid());
//
////        inventory.setState(2);
//        inventory.setUpdate_stock(1);
//        inventory.setUpdate_stock_date(new Date());
//        jxcStockInventoryMapper.updateByPrimaryKeySelective(inventory);
    }
}
